package com.gxkj.movie.filters;


import com.gxkj.movie.config.utils.SpringContextUtil;
import com.gxkj.movie.dtos.ReqLog;
import com.gxkj.movie.helpers.LogWebsiteVisitHelper;
import com.gxkj.movie.threads.ReqLogSubmiThread;
import com.gxkj.movie.utils.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.startup.Catalina;
import org.apache.commons.lang3.StringUtils;
import org.git.movie.entity.LogWebsiteVisit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.InetAddress;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.Executor;

/**
 * 由于需要配置顺序，迁移到WebConfig中配置了
 */
//@WebFilter(urlPatterns = "/*", filterName = "logFilter" )
@Slf4j
public class LogFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(LogFilter.class);



    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;

        String reqUri =  request.getRequestURI();
        String lowerreqUri = reqUri.toString().toLowerCase();
        if(lowerreqUri.indexOf(".js") >= 0 || lowerreqUri.indexOf(".css") >= 0
                || lowerreqUri.indexOf(".jpg") >= 0
                || lowerreqUri.indexOf(".png") >= 0
                || lowerreqUri.indexOf("/static/") >= 0
        ){
            try{
                chain.doFilter(request, response);

            }catch (Exception e){

                throw  e;
            }
        }else {

            String appName = "movie-java-client";
            Date now = Calendar.getInstance().getTime();
            long start = System.currentTimeMillis();
            MDC.put( "URL", reqUri);

            String method = request.getMethod();
            MDC.put( "method", method);

            String customerIp = IpUtil.getIp(request);
            MDC.put( "customerIp", customerIp);

            String userAgent = request.getHeader("user-agent");
            MDC.put( "User-Agent", userAgent);

            String  accept = request.getHeader("accept");
            MDC.put( "Accept", accept);

            String referer = request.getHeader("referer");
            MDC.put( "referer", referer);

            HttpSession session =  request.getSession();
            String sessioId = null;
            if(session != null){
                sessioId = session.getId();
            }

            MDC.put( "session", sessioId);

            String deviceId1 = request.getHeader("deviceId1");
            String deviceId1from = request.getHeader("deviceId1from");

            String deviceId2 = request.getHeader("deviceId2");
            String deviceId2from = request.getHeader("deviceId2from");


            //设备码和设备码的颁发机构，有时会使用多个设备码
            MDC.put( "deviceId1", deviceId1);
            MDC.put( "deviceId1from", deviceId1from);
            MDC.put( "deviceId2", deviceId2);
            MDC.put( "deviceId2from", deviceId2from);

            //调用方app
            String fromApp = request.getHeader("fromApp");
            MDC.put( "fromApp", fromApp);


            try{
                chain.doFilter(request, response);

            }catch (Exception e){

                throw  e;
            }finally {

                ReqLog log = new ReqLog();
                String serverIp = IpUtil.getLocalIp();
                log.setServerIp(serverIp);
                log.setTimestamp(now);
                log.setAppName(appName);
                log.setDeviceId1(deviceId1);
                log.setDeviceId1from(deviceId1from);
                log.setDeviceId2(deviceId2);
                log.setDeviceId2from(deviceId2from);
                log.setURL(reqUri);
                log.setUserAgent(userAgent);
                log.setAccept(accept);
                log.setReferer(referer);
                log.setSession(sessioId);
                log.setMethod(method);
                log.setCustomerIp(customerIp);
                log.setFromApp(fromApp);
                log.setTraceId(MDC.get("traceId"));

//                log.setUserId("1");
//                log.setUserType("test");
//                log.setDeviceId1from("bbb");
//                log.setDeviceId1("aaaa");
//                log.setTakeTime(1000L);

                long end = System.currentTimeMillis();
                log.setTakeTime(end-start);


                Executor taskPool = (Executor) SpringContextUtil.getBean("taskExecutor");
                if(taskPool != null){
                    ReqLogSubmiThread reqLogSubmiThread = new ReqLogSubmiThread(log);
                    taskPool.execute(reqLogSubmiThread);
                }


                MDC.remove("URL");
                MDC.remove("User-Agent");
                MDC.remove("Accept");
                MDC.remove("referer");
                MDC.remove("session");

                MDC.remove("method");
                MDC.remove("customerIp");


                MDC.remove("deviceId1");
                MDC.remove("deviceId1from");
                MDC.remove("deviceId2");
                MDC.remove("deviceId2from");

                MDC.remove("fromApp");
            }
        }






    }

    @Override
    public void destroy() {

    }
}